package org.example.exception;


import lombok.extern.slf4j.Slf4j;
import org.example.common.ResponseResult;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;

import java.util.List;
import java.util.stream.Collectors;

@Slf4j
//@RestControllerAdvice
public class GlobalException {
    /**
     * 自定义全局异常处理器
     *
     * @param exception 异常信息
     * @return 错误提示
     */
    @ExceptionHandler(LeadException.class)
    public ResponseResult leadExceptionHadler(LeadException exception) {
        return new ResponseResult(exception.getStatus(), exception.getMessage());
    }

    /**
     * 参数校验出现异常的处理

     */
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public ResponseResult methodArgumentNotValidExceptionHadler(MethodArgumentNotValidException exception) {
        BindingResult bindingResult = exception.getBindingResult();
        List<ObjectError> allErrors = bindingResult.getAllErrors();
        String msg = allErrors.stream().map(error -> error.getDefaultMessage()).collect(Collectors.joining(";"));
        return new ResponseResult(400, msg);
    }

    /**
     * 全局兜底的异常处理器
     *
     * @param exception 异常信息
     * @return 错误提示
     */
    @ExceptionHandler(Throwable.class)
    public ResponseResult leadExceptionHadler(Throwable exception) {
        return new ResponseResult(500, "服务端异常，请稍后重试");
    }
}
